<template>
  <c-card isAffix>
    <c-table
      row-key="_id"
      class="table-template__table"
      :loading="loading"
      :data="tableData"
      v-model:search="searchParams"
      v-model:paging="paging"
      @refresh="queryTableData"
    >
      <!-- 搜索栏 -->
      <!-- <template #search>
        <c-input v-model="searchParams.userid" placeholder="请输入userid" />
      </template> -->

      <!-- 操作栏 -->
      <!-- <template #handle="{}">
        <el-button type="primary" @click="hanleModal">添加商品</el-button>
      </template> -->

      <!-- 表格 -->
      <template #table>
        <el-table-column prop="_id" label="ID" width="120"> </el-table-column>
        <el-table-column prop="product_name" label="用户信息" min-width="320">
          <template #default="{ row }">
            <div class="product">
              <el-image class="product-img" :src="row.user_info.avatar" fit="cover" />
              <div class="product-right">
                <div class="product-name">
                  {{ row.user_info.nickname }}
                </div>
                <div class="product-score">ID：{{ row.user_info._id }}</div>
                <div class="product-score">剩余积分：{{ row.user_info.score }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="product_name" label="商品信息" min-width="360">
          <template #default="{ row }">
            <div class="product">
              <el-image
                class="product-img"
                :src="row.product_info.product_imgs[0]"
                :preview-src-list="row.product_info.product_imgs"
                preview-teleported
                hide-on-click-modal
                fit="cover"
              />
              <div class="product-right">
                <div class="product-name">
                  {{ row.product_info.product_name }}
                  <el-tag v-if="row.product_info.is_new">新人专享</el-tag>
                </div>
                <div class="product-score">商品ID：{{ row.product_info._id }}</div>
                <div class="product-score">积分：{{ row.product_info.score_count }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="用户联系方式" prop="wechat_number" min-width="180">
          <template #default="{ row }">
            <div>用户备注：{{ row.remark || '-' }}</div>
            <div>联系方式：{{ row.wechat_number || '-' }}</div>
            <div>
              下单时间：
              {{ dayjs(row.create_time).format('YYYY-MM-DD HH:mm:ss') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" min-width="180">
          <template #default="{ row }">
            <span class="is-warning-text" v-if="row.status == 1">待兑换</span>
            <span class="is-success-text" v-if="row.status == 2">已兑换</span>
            <div v-if="row.update_time">
              {{ dayjs(row.update_time).format('YYYY-MM-DD HH:mm:ss') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="兑换信息" min-width="240">
          <template #default="{ row }">
            <div v-if="row.use_remark" v-html="richImgAuto(row.use_remark)"></div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="{ row }">
            <el-button text type="primary" @click="hanleExchangeModal(row)">去兑换</el-button>
            <el-button type="danger" text @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </template>
    </c-table>

    <!-- 弹窗 -->
    <c-dialog title="订单兑换" :width="800" name="mall-exchange-popup">
      <mall-exchange-popup @refresh="queryTableData"></mall-exchange-popup>
    </c-dialog>
  </c-card>
</template>

<script setup name="el-encap.table-template">
import { ref, computed, onMounted } from 'vue';

// hooks
import { useTable } from '@/hooks/useTable/index.js';
import { useFetch } from '@/hooks/useFetch/index.js';

// components
import { MessageBox } from '@/utils/message-box';
import { ElMessage } from 'element-plus';
import Sortable from 'sortablejs';
import MallExchangePopup from './components/mall-exchange-popup.vue';

// router
import { useRouter } from 'vue-router';
const router = useRouter();

// store modal
import { useModalStore } from '@/pinia/modules/modal';
const modalStore = useModalStore();

// user
import { useUserStore } from '@/pinia/modules/user.js';
const userStore = useUserStore();

import { pageListUserLog } from '@/apis/user';
import {
  getProductOrderList,
  setProductStatus,
  delOrder,
  setProductWeight,
} from '@/apis/product.js';

import { UserPlatform } from '@/config/global-variable';

import dayjs from 'dayjs';

// 表格相关
const { loading, paging, searchParams, tableData, queryTableData, delTableRow } = useTable({
  api: getProductOrderList,
  params: {
    uni_platform: '',
    userid: '',
  },
  options: {},
  callBack: () => {},
});

const hanleModal = () => {
  modalStore.openModal('mall-exchange-popup');
};

const hanleExchangeModal = (row) => {
  modalStore.openModal('mall-exchange-popup', row);
};

// 状态开关
const switchBeforeChange = async (row) => {
  return await setProductStatus({ _id: row._id, status: row.status == 1 ? 0 : 1 }).catch(
    (err) => err,
  );
};

// 删除
const handleDelete = (row) => {
  delTableRow({
    api: delOrder,
    params: { _id: row._id },
  });
};

const richImgAuto = (html) => {
  return html.replace('<img', '<img style="max-width:60%;height:auto" '); //替换
};

// 行拖拽
const rowDrop = () => {
  const tbody = document.querySelector('.table-template__table tbody');
  Sortable.create(tbody, {
    group: {
      name: 'shared',
      pull: true,
      put: true,
    },
    handle: '.table-drag-img',
    animation: 150,
    async onEnd({ newIndex, oldIndex }) {
      console.log(newIndex, oldIndex, 'newIndex, oldIndex');

      const currRow = tableData.value.splice(oldIndex, 1)[0];

      tableData.value.splice(newIndex, 0, currRow);

      let allList = [];
      for (let index = 0; index < tableData.value.length; index++) {
        const item = tableData.value[index];
        console.log(item, index, 'index');

        allList.push(setProductWeight({ _id: item._id, weight: index }));
      }

      loading.value = true;
      await Promise.all(allList);
      loading.value = false;

      queryTableData();
    },
  });
};

onMounted(() => {});
</script>

<style lang="scss" scoped>
.product {
  display: flex;
  align-items: center;

  .product-img {
    width: 60px;
    height: 60px;
    border-radius: 4px;
    margin-right: 10px;
    flex-shrink: 0;
  }

  .product-right {
    display: flex;
    flex-direction: column;
  }

  .product-name {
    font-size: 14px;
  }

  .product-score {
  }
}
</style>
